package cn.itcast.order.jobHandler;

/**
 * @author oldwine
 * @date 2022/6/23
 * @Version 1.0
 */


import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.order.mapper.OrderDetailMapper;
import cn.itcast.order.service.OrderDetailService;
import cn.itcast.order.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * 订单定时任务
 */
@Slf4j
@Component
public class OrderJob {
    private static Logger logger = LoggerFactory.getLogger(OrderJob.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ItemClient itemClient;

    @XxlJob("oldwine_job_order_outtime")
    public void clearOutTimeOrder() {
        //1.查询所有订单 检查订单的支付状态
        List<Order> orders = orderService.list();
        //遍历订单集合,获取订单状态
        for (Order order : orders) {
            Long orderId = order.getId();
            Integer status = order.getStatus();
            Instant now = Instant.now(); //获取当前时间
            Date createTime = order.getCreateTime();
            Instant creatTime = Instant.ofEpochMilli(createTime.getTime()); //获取订单创建时间

            //判断订单状态  如果订单状态为1且时间超过 2分钟,
            if (status == 1 && (Duration.between(creatTime, now).toMillis()) / (1000 * 60) >= 2) {
                // 将订单状态设置为 5 同时根据商品id将库存恢复
                order.setStatus(5);
                order.setEndTime(new Date());
                order.setCloseTime(new Date());
                orderService.saveOrUpdate(order);

                //查询订单详情表 ,获得商品数量
                LambdaQueryWrapper<OrderDetail> wrapper = Wrappers.lambdaQuery(OrderDetail.class);
                wrapper.eq(OrderDetail::getOrderId, orderId);
                OrderDetail orderDetail = orderDetailMapper.selectOne(wrapper);
                Long itemId = orderDetail.getItemId();
                Integer num = orderDetail.getNum();

                //远程调用添加库存方法
                itemClient.addStock(itemId, num);
                log.info("定时任务启动中....");
            }
        }
    }

    @XxlJob("oldwine_job_test")
    public void jobTest() {
        System.out.println("jobTest run.....");
    }

    public void init() {
        logger.info("init");
    }

    public void destroy() {
        logger.info("destory");
    }


}
